package com.alon.spring01.study;


import com.alibaba.fastjson.JSON;
import com.alon.spring01.model.Country;

import java.text.Collator;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.Stream.Builder;

import com.alon.spring01.model.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

/**
 * @program: spring01
 * @description: java1.8特性
 * @author: yulongguang
 * @create: 2019-05-04 22:32
 **/
@Slf4j
public class java18Test {

    private static <T> Predicate<T> notEqual(T t) {
        return (v) -> !Objects.equals(v, t);
    }

    public static void main(String[] args) {

//        List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Alon");
//        features.forEach(n -> System.out.println(n));

//        String a="日本1";
//        List<Country> countries=new ArrayList<>();
//        for (int i=0;i<10;i++){
//            Country country=new Country();
//            country.setCountryname("日本"+i);
//            country.setCountrycode("02"+i);
//            countries.add(country);
//        }
//        countries.forEach(n-> System.out.println(n));
//        List<Country> countryList=countries.stream().filter((country)->country.getCountryname().equals(a)).collect(
//                Collectors.toList());
//        System.out.println(JSON.toJSONString(countryList));
//       countries.stream().map(e->{e.setCountryname("131313");return e;}).forEach(e-> System.out
//               .println(e));

        List<Country> names = new ArrayList<>();
        Country country = new Country();
        country.setCountryname("北京");
        names.add(country);
        Country c1 = new Country();
        c1.setCountryname("上海");
        names.add(c1);
        Country c2 = new Country();
        c2.setCountryname("重庆");
        names.add(c2);
        Country c3 = new Country();
        c3.setCountryname("上海");
        names.add(c3);
        Country c4 = new Country();
        c4.setCountryname("阿里巴巴");
        names.add(c4);
        Country c5 = new Country();
        c5.setCountryname("草泥马");
        c5.setCountrycode("021");
        names.add(c5);
        Country c6 = new Country();
        c6.setCountryname("草泥马");
        names.add(c6);
        List<User> users = new ArrayList<>();
        User user = new User();
        user.setUserName("阿龙哥");
        users.add(user);
        c1.setUsers(users);

//        sortUsingJava8(names);
        //忽略首字母大小
//        names.sort(String.CASE_INSENSITIVE_ORDER);
//        log.info("排序后的集合，{}",JSON.toJSONString(names));
//        //对首字母大小写敏感
//        names.sort(Comparator.naturalOrder());
        log.info("中文排序后的集合，{}", JSON.toJSONString(names));

        if (CollectionUtils.isNotEmpty(names)) {
            names.stream().sorted(Comparator.comparing(Country::getCountryname))
                    .collect(Collectors.toList());
        }
        log.info("中文排序后的集合，{}", JSON.toJSONString(names));

        names.sort(Comparator.comparing(Country::getCountryname, String.CASE_INSENSITIVE_ORDER));
        log.info("中文排序后的集合，{}", JSON.toJSONString(names));
        Collator collator = Collator.getInstance();
        collator.setStrength(Collator.PRIMARY);
        names.sort(Comparator.comparing(Country::getCountryname, collator));
        log.info("中文排序后的集合，{}", JSON.toJSONString(names));
        names.stream().sorted((o1, o2) -> Collator.getInstance(Locale.CHINESE).compare(o1.getCountryname(), o2.getCountryname())).collect(Collectors.toList());
        log.info("中文排序后的集合，{}", JSON.toJSONString(names));
        //遍历并判断
        names.stream().filter(u -> u.getCountryname().equals("草泥马")).forEach(u -> {
            System.out.println("u" + u.getCountryname());
        });
        names.stream().forEach(u -> {
            System.out.println(u.getCountryname());
        });
        //map
        names.stream().map(Country::getCountryname).forEach(u -> {
            System.out.println("u1" + u);
        });
        //计算总数
        int sum = names.stream().filter(b -> CollectionUtils.isNotEmpty(b.getUsers())).mapToInt(b -> b.getUsers().size()).sum();
        log.info("sum,{}", sum);
        //flatMap
        names.stream().forEach(u -> {
            log.info("u.getCountryname():{}", u.getCountryname());
            Optional.ofNullable(u.getUsers()).ifPresent(a -> {
                //do something
                a.stream().forEach(b -> {
                    log.info("userName:{}", b.getUserName());
                });
            });
        });
        names.stream().filter(us -> CollectionUtils.isNotEmpty(us.getUsers())).flatMap(u -> u.getUsers().stream()).forEach(b -> {
            log.info("b.getUserName():{}", b.getUserName());
        });
        //flatMapToInt
        int sum1 = names.stream().filter(us -> CollectionUtils.isNotEmpty(us.getUsers())).flatMapToInt(u -> IntStream.of(u.getUsers().size())).sum();
        log.info("sum1：{}", sum1);
        //peek 相当于break
        List<Country> collect = names.stream().filter(c -> CollectionUtils.isNotEmpty(c.getUsers())).peek(c -> log.info("c.getCountryname():{},c.getUsers().size():{}", c.getCountryname(), c.getUsers().size()))
                .collect(Collectors.toList());
        log.info("=================================");
        collect.forEach(u->{
            log.info("c.getCountryname():{},c.getUsers().size():{}",u.getCountryname(),u.getUsers().size());
        });
        //anyMatch-->在找到与predicate匹配的元素会返回ture
        boolean anyMatch = names.stream().filter(u -> u.getCountryname().equals("草泥马")).peek(u -> {
            log.info("peek.u.getCountryname():{}", u.getCountryname());
        }).anyMatch(b -> b.getCountryname().equals("草泥马"));
        log.info("anyMatch:{}",anyMatch);
        //allMatch 在找到满不足predicate的任意一个元素会返回false,否则返回true
        boolean allMatch = names.stream().filter(u -> u.getCountryname().equals("草泥马")).peek(u -> {
            log.info("peek.u.getCountryname():{}", u.getCountryname());
        }).allMatch(b -> b.getCountryname().equals("草泥马"));
        log.info("allMatch:{}",allMatch);
        //noneMatch 如果找到任意一个满足predicate的元素时会返回false,否则返回true
        boolean noneMatch = names.stream().filter(u -> u.getCountryname().equals("草泥马")).peek(u -> {
            log.info("peek.u.getCountryname():{}", u.getCountryname());
        }).noneMatch(b -> b.getCountryname().equals("草泥马"));
        log.info("noneMatch:{}",noneMatch);
        //findFist()
        Country country1 = names.stream().findFirst().get();
        log.info("country1.getCountryname():{}",country1.getCountryname());
        Country country2 = names.stream().findAny().get();
        log.info("country2.getCountryname():{}",country2.getCountryname());

        List<String > list1=new ArrayList<>();
        list1.add("12313131312313");
        Optional.ofNullable(list1).ifPresent(u->{
            u.forEach(a->{

            });

        });

       names = names.stream().filter(distinctByKey(o -> o.getCountryname()))
                .collect(Collectors.toList());
        System.out.println("names:"+JSON.toJSONString(names));

        StringJoiner roleJoiner = new StringJoiner(",");
        names.stream().filter(u->u.getCountryname().equals("草泥马")).forEach(p->{
            roleJoiner.add(p.getCountryname()).add(p.getCountrycode());
        });
        System.out.println("s:"+roleJoiner.toString());
        StringJoiner strJoiner = new StringJoiner(",");
        names.stream().filter(u->u.getCountryname().equals("111")).forEach(p->{
            strJoiner.add(p.getCountryname()).add(p.getCountrycode());
        });
        System.out.println("s:"+strJoiner.toString());

        IntStream.range(0,names.size()).forEach(i->{
            System.out.println("i + i :"+i);
        });

        String ids="1,";
        String[] split = ids.split(",");
        Arrays.stream(split).forEach(p-> System.out.println("ppppp"+p));
        String baseExeUsers = Arrays.stream(split).filter(p -> "2".equals(p) ).map(u->u).collect(Collectors.joining(","));
        System.out.println("baseExeUsers"+baseExeUsers);
        StringBuilder stringBuilder=new StringBuilder();
        System.out.println("13131"+stringBuilder.toString());
    }


    /**
     * java8 排序
     */
    private static void sortUsingJava8(List<String> names) {
        Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
